<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Http\model\Sms;
use App\Http\Controllers\AlipayController; 
/**
* 下单控制器
*/
class SetorderController extends Controller
{
	/*
		历史乘车人
		Get
		uid  用户id
		page 页数

	*/
	public function busrider(Request $request)
	{
		$uid = $request->get('id'); 
		$users = DB::table('order')->where('user_id',$uid)->select('peer')->get();
		$users = json_decode(json_encode($users),true);
		foreach ($users as $key => &$value) {
			$value['peer'] = json_decode($value['peer'],true);
		}
		$arr = [
			'code'=>'1000',
			'data'=>$users
		];
		echo json_encode($arr);
	}
	/*
	选择城市：已开通服务城市
	*/
	public function chosecity(Request $request)
	{
		//拿到即时用车id
		$server = Db :: table('server_item')->where('name','即时用车')->first();
		$serid = $server -> id;
		//dump($serid);
		$area = Db :: table('company_server_car')
			->leftJoin('region','company_server_car.area_id','=','region.code')
			->where('company_server_car.item_id',$serid)
			->select('region.name','region.code')
			->get();
		$area = json_decode(json_encode($area),true);
		//dump($area);
		$arr = [];
    $i = 0;
		foreach ($area as $key => $value) {
      $arr[$i]['name'] = $value['name'];
			$arr[$i]['code'] = $value['code'];
      $i++;
		}
		//dump($arr);
		$returnArr = [
			'code'=>'1000',
			'data'=>$arr
		];
		echo json_encode($returnArr);
	}
	/*
		返回车系
		fullname  北京市
		type       即时用车
	*/
	public function carserver(Request $request)
	{
		$fullName = $request -> input('fullname');
		$type = $request -> input('type');
		//拿到即时用车id
		$server = Db :: table('server_item')->where('name',$type)->first();
		$serid = $server -> id;
		//拿到区域code
		$area = Db :: table('region')->where('fullName',$fullName)->first();
		$code = $area -> code;
		//拿到车系id
		$car = Db :: table('company_server_car')->where('item_id',$serid)->where('area_id',$code)->first();
		if(!empty($car)){
			$car = $car -> series_id;
			//拿取车系信息
			$car = explode(',', $car);
			$cararr = Db :: table('car_series')
							->whereIn('id',$car)->where('status',1)->select('id','series_name','image','people')->get();
			$cararr = json_decode(json_encode($cararr),true);
			$arr = [
				'code'=>'1000',
				'data'=>$cararr
			];
		}else{
			$arr = [
				'code'=>'1001',
				'data'=>'暂无数据'
			];
		}
		
		echo json_encode($arr);
	}
	/*
		下单
	*/
	public function order(Request $request)
	{

		$data = $request -> all();
		$uid = $request->get('id');;//用户id
		//$uid = 148;
		// dump($uid);
     //个人或者公司
        if(!empty($data['perOrCom'])){
          if($data['perOrCom'] == 1){//个人
              $statusArr = [9,10,11];
              $clearing_type = Db :: table('order')
                              ->where('user_id',$uid)
                              ->where('judgment',5)->whereIn('status',$statusArr)->where('wystatus',1)->first();
              $clearing_type = json_decode(json_encode($clearing_type),true);
          }else{
              $company_id = Db :: table('social_user')->where('id',$uid)->select('company_id')->first();
              $statusArr = [9,10,11];
              $clearing_type = Db :: table('order')
                              ->where('companyId',$company_id -> company_id)
                              ->where('judgment',5)->whereIn('status',$statusArr)->where('wystatus',1)->first();
              $clearing_type = json_decode(json_encode($clearing_type),true);
          }
        }else{
          $statusArr = [9,10,11];
          $clearing_type = Db :: table('order')
                              ->where('user_id',$uid)
                              ->where('judgment',5)->whereIn('status',$statusArr)->where('wystatus',1)->first();
          $clearing_type = json_decode(json_encode($clearing_type),true);
        }
		
        //dump($clearing_type);
        if($clearing_type){
        	$return['code'] = '1001';
            $return['msg'] = '有订单尚未结算';
            echo json_encode($return);
            die;
        }
        //拿取服务类型的id
       	$type = $data['type'];//服务中文名
       	if($type == '接机'){
       		$cip = 1;
       	}else{
       		$cip = 2;
       	}
       	$server = Db :: table('server_item')->where('name',$type)->first();
		$serid = $server -> id;
		//dump($serid);
		//生成订单号
        $num = date('ymds') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 7);
        //拿下单人信息
       	$user = Db :: table('social_user')->where('id',$uid)->first();
       	// dump($user);
       	$nickname = $user -> nickname;
       	// dump($nickname);
       	$phone = $user -> phone;
       	// dump(	$phone);
       	//是否本人乘车;1本人2其他人
       	$isself = $data['isself'];
       	if($isself == 1){
       		$carpeople = $nickname;
       		$carphone = $phone;
       	}else{
       		if($data['carpeople'] == '本人乘车'){
       			$carpeople = '乘客' . rand(111,999);
       		}else{
       			$carpeople = $data['carpeople'];
       		}
       		$carphone = $data['carphone'];
       	}
       	//同行人信息
       	if($data['passenger_people'] > 1){
       		$peer = json_encode($data['peer']);//同行人信息：姓名，电话
       	}else{
       		$peer = '';
       	}
       	//cip人数
       	if(!empty($data['cip_number'])){
       		$cip_number = $data['cip_number'];
       	}else{
       		$cip_number = '';
       	}
       	//付款来源
       	$pay_from = $data['pay_from'];
       	//备注
       	$remarks = $data['remarks'];
       	//航班号
       	if(!empty($data['flight_number'])){
       		$flight_number = $data['flight_number'];
       	}else{
       		$flight_number = '';
       	}
       	//航站楼
       	if(!empty($data['terminal'])){
       		$terminal = $data['terminal'];
       	}else{
       		$terminal = '';
       	}
       	//火车车次
       	if(!empty($data['car_trips'])){
       		$car_trips = $data['car_trips'];
       	}else{
       		$car_trips = '';
       	}
       	//火车车站
       	if(!empty($data['station'])){
       		$station = $data['station'];
       	}else{
       		$station = '';
       	}
       	//是否使用接送机
       	if(!empty($data['jsjcs'])){
       		$jsjcs = 2;
       	}else{
       		$jsjcs = 1;
       	}
       	//cip乘车人信息
       	if(!empty($data['cippeople'])){
       		$cippeople = json_encode($data['cippeople']);
       	}else{
       		$cippeople = '';
       	}
       	$area = Db :: table('region')->where('code',$data['area_code'])->first();
		    $areaid = $area -> parentCode;
        //个人或者公司
        if(!empty($data['perOrCom'])){
          if($data['perOrCom'] == 1){//个人
              $companyId = '';
          }else{
             $company_id = Db :: table('social_user')->where('id',$uid)->select('company_id')->first();
             $companyId = $company_id -> company_id;
          }
        }else{
          $companyId = '';
        }
        //是否使用接送机
        if(!empty($data['usejsj'])){
            if($data['usejsj'] == 0){//企业规则
                $jsjcs_type = 0;
            }elseif ($data['usejsj'] == 1) {//个人剩余
                $jsjcs_type = 1;
            }
        }else{
          $jsjcs_type = 2;
        }
        $insertArr = [
        	  'user_id'=>$uid,// int(11) NOT NULL COMMENT '用户id',
			//  'hotel_id'=>, //int(11) DEFAULT NULL COMMENT '酒店ID',
			  'car_id'=>$data['car_id'],//int(11) DEFAULT NULL COMMENT '车系ID',
			  'order_number'=>$num, //varchar(20) NOT NULL DEFAULT '' COMMENT '订单编号',
			  'end'=>$data['end'],// varchar(100) NOT NULL COMMENT '终点地址',
			  'origin'=>$data['origin'],// varchar(100) NOT NULL COMMENT '起点地址',
			  //'difprice'=>,// decimal(10,2) DEFAULT NULL COMMENT '真实价和预估价的差值',
			  //'true_price'=>,// decimal(10,2) DEFAULT NULL COMMENT '订单真实价格',
			  'price'=>$data['price'],// int(10) NOT NULL COMMENT '价格',
			  'type'=>$serid,// tinyint(2) NOT NULL COMMENT '所选服务id，，，server_item的id',
			  'orders_name'=>$nickname,// varchar(100) DEFAULT NULL COMMENT '下单人姓名',
			  'orders_phone'=>$phone,// varchar(11) NOT NULL DEFAULT '0' COMMENT '下单人手机',
			  'appointment'=>strtotime($data['appointment']),// int(11) NOT NULL COMMENT '用车时间',
			  'passenger_name'=>$carpeople,// varchar(100) DEFAULT NULL COMMENT '乘客姓名',
			  'passenger_phone'=>$carphone,// varchar(11) DEFAULT NULL COMMENT '乘客手机',
			  'passenger_people'=>$data['passenger_people'],// varchar(11) DEFAULT '0' COMMENT '乘车人数',
			  //'bottom_number'=>,// varchar(255) DEFAULT NULL COMMENT '酒店单号',
			  //'room_number'=>,// varchar(11) DEFAULT NULL COMMENT '房间号',
			 // 'chauffeur_name'=>,// varchar(100) DEFAULT NULL COMMENT '司机姓名',
			  //'chauffeur_phone'=>,// varchar(11) DEFAULT NULL COMMENT '司机手机',
			  'cip'=>$cip,// tinyint(1) NOT NULL DEFAULT '2' COMMENT '是否接机 1 接 2  不接',
			  'created_at'=>time(),// int(11) NOT NULL COMMENT '创建时间',
			  'status'=>1,// tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态 0 已取消 1 待执行  2-8执行中   9 完成  10 待审核  11等待财务确定',
			  'wystatus'=>1,// tinyint(1) DEFAULT '1' COMMENT '网约车订单结算状态，1未结算；2结算',
			 // 'chauffeur_id'=>,// int(11) DEFAULT NULL COMMENT '对应司机ID',
			  'remarks'=>$remarks,// text COMMENT '备注',
			  'origin_position'=>$data['origin_position'],// varchar(20) NOT NULL COMMENT '起点经纬度',
			  'end_position'=>$data['end_position'],// varchar(20) NOT NULL DEFAULT '' COMMENT '终点经纬度',
			  //'complete_at'=>,// int(11) DEFAULT NULL COMMENT '完成时间',
			  'judgment'=>5,// tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '类型 1 为app端创建 2 为后台创建 3 为酒店前台创建 4 为网约车小程序创建 5社会化用车',
			  //'mileage'=>,// varchar(20) DEFAULT NULL COMMENT '里程',
			  //'send_id'=>,// int(11) DEFAULT NULL COMMENT '派单员id',
			 // 'send_type'=>,// int(11) DEFAULT NULL COMMENT '派单类型 1 系统后台，2组织前台',
			 // 'clearing_type'=>,// int(11) NOT NULL DEFAULT '1' COMMENT '结算状态（1，未结算 2，已结算  3，结算确认中）',
			 // 'custom'=>,// int(11) NOT NULL DEFAULT '0' COMMENT '定制类型 1孕妈用车 2商务用车 3会展用车 4会议用车 5婚庆用车 6其他',
			 // 'pay_status'=>,// int(11) DEFAULT '1' COMMENT '1 未支付 2已支付 3已取消',
			  'cip_number'=>$cip_number,// varchar(20) DEFAULT NULL COMMENT 'CIP人数',
			  //'service_type'=>,// tinyint(2) DEFAULT '1' COMMENT '服务类型：1 市场服务 2 内部服务',
			  //'resource'=>,// tinyint(2) DEFAULT '0' COMMENT '自营为0,合作机构为1',
			 // 'cooperation_id'=>,// int(11) DEFAULT NULL COMMENT '合作机构ID',
			 // 'cost_price'=>,// int(11) DEFAULT '0' COMMENT '成本价',
			  //'takeout_manage_car'=>,// int(11) unsigned DEFAULT NULL COMMENT '合作机构车辆ID',
			  'pay_from'=>$pay_from,// tinyint(2) unsigned DEFAULT '0' COMMENT '付款来源:0=企业,1=个人,2=接送机次数',
			  'flight_number'=>$flight_number,// varchar(200) DEFAULT NULL COMMENT '航班号',
			  'terminal'=>$terminal,// varchar(255) DEFAULT NULL COMMENT '航站楼',
			  'car_trips'=>$car_trips,// varchar(50) DEFAULT NULL COMMENT '火车车次',
			  'station'=>$station,// varchar(255) DEFAULT NULL COMMENT '火车车站',
			  'jsjcs'=>$jsjcs,// int(2) DEFAULT '1' COMMENT '是否使用接送机次数抵扣（2是，1否）',
			  'peer'=>$peer,// longtext COMMENT '同行人信息：姓名，电话；json_encode存入',
			  'cippeople'=>$cippeople,// longtext COMMENT 'cip乘车人信息',
			  'companyId'=>$companyId,// int(10) DEFAULT NULL COMMENT '企业关联id',
			  'jsjcs_type'=>$jsjcs_type,// int(2) DEFAULT '2' COMMENT '接送机使用方式（0：企业规则 ，1：个人剩余，2：不使用）',
			  'area_code'=>$areaid,// varchar(255) DEFAULT NULL COMMENT '社会化用车个人版，默认北京区域code',
        ];
        //是否使用接送机
        if(!empty($data['usejsj'])){
            if($data['usejsj'] == 0){//企业规则
              $price = $data['fuwurice'];
            }elseif ($data['usejsj'] == 1) {//个人剩余
              $price = $data['fuwurice'];
            }
        }else{
              $price = $data['price'];
        }
        DB::beginTransaction();
        try {
        	$id = Db :: table('order')->insertGetId($insertArr);
          //个人或者公司
          if(!empty($data['perOrCom'])){
            if($data['perOrCom'] == 1){//个人
              if(!empty($data['payType'])){
                  if(!empty($data['usejsj'])){
                      if($data['usejsj'] == 0){//企业规则
                        Db :: table('social_user')->where('id',$uid)->decrement('plane_left_num');
                        Db :: table('social_user')->where('id',$uid)->increment('plane_used_num');
                      }elseif ($data['usejsj'] == 1) {//个人剩余
                        Db :: table('social_user')->where('id',$uid)->decrement('p_plane_left_num');
                        Db :: table('social_user')->where('id',$uid)->increment('p_plane_used_num');
                      }
                  }
                //个人支付
                if($data['payType'] == 1){
                   $card = Db :: table('wakeup_card')
                              ->where('uid',$uid)
                              ->where('from',2)
                              ->where('lost_price','>',$price)
                              ->order('type desc')
                              ->get();
                  $card = json_decode(json_encode($card),true);
                  if(!empty($card)){
                    Db :: table('order')->where('id',$id)->update(['cardnum'=>$card[0]['id']]);
                    Db :: table('wakeup_card')
                      ->where('id',$card[0]['id'])
                      ->decrement('lost_price',$price);
                  }else{
                   Db :: table('social_user')
                    ->where('id',$uid)
                    ->decrement('sum_money',$price);
                  } 
                }elseif($data['payType'] == 2){//企业支付
                    Db :: table('social_user')->where('id',$uid)->decrement('left_price',$price);
                    Db :: table('social_user')->where('id',$uid)->increment('used_price',$price);
                }
              }
              
            }else{//公司
               if(!empty($data['usejsj'])){
                  Db :: table('social_company')->where('id',$companyId)->decrement('plane_left_num');
                  Db :: table('social_company')->where('id',$companyId)->increment('plane_used_num');
               }
               $card = Db:: table('wakeup_card')
                    ->where('uid', $companyId)
                    ->where('from', 1)
                    ->where('lost_price', '>', $price)
                    ->order('type desc')
                    ->get();
                 $card = json_decode(json_encode($card),true);
                 if(!empty($card)){
                    Db :: table('order')->where('id',$id)->update(['cardnum'=>$card[0]['id']]);
                    Db:: table('wakeup_card')
                        ->where('id', $card[0]['id'])
                        ->decrement('lost_price',$price);
                 }else{
                    Db:: table('social_company')
                        ->where('id',$companyId)
                        ->decrement('account_money',$price);
                 }
            }
          }else{
            Db :: table('social_user')->where('id',$uid)->decrement('sum_money',$price);
          }
        	DB::commit();
        } catch (\Exception $e) {
        	DB::rollBack();
        	 $arr= [
            'id'=>'',
	        	'code'=>'1001',
	        	'msg'=>'failed',
	        ];
	        echo json_encode($arr);
	        die;
        }
        if($data['sendsms'] == 2){//1不发短信，2发短信
	        $msg = '您预订'.$data['appointment'].'的'.$type.'订单下单成功，稍后将有专属司机为您服务。【时代出行】';
	        $code = new Sms();
	        $re = $code -> sendSMS($phone,$msg);
        }
        
        $arr= [
          'id'=>$id,
        	'code'=>'1000',
        	'msg'=>'success',
        ];
        echo json_encode($arr);
	}

	public function test(Request $request)
	{
		// $c= $request->get('password');
		// dump($c);
		// $a = JWTAuth::parseToken()->authenticate();
		// dump($a);

	}	
	/**
     * @param  [type] $type         1包时，2里程
     * @param  [type] $origins      array,起点经纬度，[纬，经]
     * @param  [type] $destinations array,终点经纬度，[纬，经]
     * @param  [type] $usetime      用车时间
     * @param  [type] $carid        车系id
     * @param  [type] $serid        服务id
     * @param  [type] $areaid       地区id
     */
    public function fee2($origins, $destinations, $usetime, $carid, $serid, $areaid)
    {
        $ori = implode(',', $origins);
        $des = implode(',', $destinations);
        $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $ori . '&destinations=' . $des . '&ak=RGwhFRkSZfva32BN96csoObm4FIfiCAY';
        // return  $url;
        $result = $this->get_curl_json($url);
       // dump($result);
        $time = round($result['result'][0]['duration']['value'] / 60);//时间
       // dump($time);
        $dis = round($result['result'][0]['distance']['value']/1000, 1);//距离
       // dump($dis);
        $return = [];
        $price = 0;
        
        $re = Db:: table('company_charges_rule')->where('series_id', $carid)->where('server_id', $serid)->where('area_id', $areaid)->first();
        //dump($re);
        $re = json_decode(json_encode($re),true);
        if (!empty($re)) {
            $difdis = $dis - $re['basis_km'];//实际距离与后台设置距离差
            //dump($difdis);
            if ($difdis > 0) {//实际距离大
                $difdis2 = $dis - $re['super_km_km'];//超过多少公里以后
               // dump($difdis2);
                if ($difdis2 < $re['super_km_shortage_km']) {//不做多少公里不计费
                    $price = $re['price'];
                    //dump($price);
                } else {//计算白天和夜间的超公里收费
                    $usetime1 = explode(' ', $usetime);
                    $usetime2 = strtotime($usetime);
                    $day_start_time = strtotime($usetime1[0] . $re['day_start_time']);
                    $day_end_time = strtotime($usetime1[0] . $re['day_end_time']);
                    $avgdis = $difdis2 / $re['super_km_per_km'];
                   // dump($avgdis);
                    if ($day_start_time < $usetime2 && $usetime2 < $day_end_time) {
                        $price = $re['price'] + $avgdis * $re['day_commission'];
                        //dump($price);
                    } else {
                        $price = $re['price'] + $avgdis * $re['night_commission'];
                    }
                }
            } else {//实际距离小
                $price = $re['price'];
            }
            $diftime = $time - $re['basis_time'];
            //dump($diftime);
            if ($diftime > 0) {//超时
                $diftime2 = $time - $re['starting_starting_time'];//起步后多少分钟内不收费
                if ($diftime2 < 0) {
                    $price = $price;
                } else {
                    $diftime3 = $diftime2 - $re['starting_shortage_time'];
                    if ($diftime3 < 0) {
                        $price = $price;
                    } else {
                        if($re['starting_exceed_time'] > 0){
                            $avgtime = $diftime3 / $re['starting_exceed_time'];
                        }else{
                            $avgtime = $diftime3;
                        }
                        
                        $price = $price + $avgtime * $re['starting_add_money'];
                    }
                }
            } else {//不超时
                $price = $price;
                //dump($price);
            }
            $return['price'] = sprintf("%.2f",$price); 
            $return['msg'] = 'success';
        } else {
            $return['price'] = 0;
            $return['msg'] = '没有该服务';
        }
        return $return;
    }
    //计算价格
    function price(Request $request)
    {
        $data = $request -> all();
        //dump($data);
        $server = Db :: table('server_item')->where('name',$data['type'])->first();
		$serid = $server -> id;
        $origins = [$data['latshang'], $data['lngshang']];
        $destinations = [$data['lat'], $data['lng']];
        $usetime = $data['usetime'];
        $carid = $data['carid'];
        //$serid = $data['serid'];
        $areaid = $data['areaid'];
        $area = Db :: table('region')->where('code',$areaid)->first();
		$areaid = $area -> parentCode;
        $re = $this->fee2($origins, $destinations, $usetime, $carid, $serid, $areaid);
        //dump($re);
       // $re['price'] = 2;
        echo json_encode($re);
    }
    //叼起支付宝支付
    /*
	@param string $orderId   商品订单ID 
     * @param string $subject   支付商品的标题 
     * @param string $body      支付商品描述 
     * @param float $pre_price  商品总支付金额 
     * @param int $expire       支付交易时间 
     * @return bool|string  返回支付宝签名后订单信息，否则返回false 
    */
    public function zhifubao(Request $request)
    {
    	$data = $request -> all();
    	$uid = $request->get('id'); 
    	$orderId = $uid.date("YmdHis",time()).rand(1111,9999);
    	$subject = '时代出行支付';
    	$body = '时代出行支付';
    	$pre_price = $data['price'];
    	$expire = date('Y-m-d H:i:s',time());
    	$pay = new AlipayController();
    	$re = $pay->unifiedorder($orderId, $subject,$body,$pre_price,$expire);
      dump($re);
      $a = json_decode($re,true);
      dump($a);
    	return $re;
    }
    //支付宝异步通知
    public function notify()
    {
    	include_once ('../../alipay/AopSdk.php');  
  		include_once ('../../alipay/aop/AopClient.php'); 
		//验证签名  
		$aop = new \AopClient();  
		$aop->alipayrsaPublicKey = \Comm\Pay\Alipay::ALIPAY_RSA_PUBLIC_KEY;  
		$flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");  
		  
		//验签  
		if($flag){  
		    //处理业务，并从$_POST中提取需要的参数内容  
		    if($_POST['trade_status'] == 'TRADE_SUCCESS'  
		        || $_POST['trade_status'] == 'TRADE_FINISHED'){//处理交易完成或者支付成功的通知  
		        //获取订单号  
		        $orderId = $_POST['out_trade_no'];  
		        //交易号  
		        $trade_no = $_POST['trade_no'];  
		        //订单支付时间  
		        $gmt_payment = $_POST['gmt_payment'];  
		        //转换为时间戳  
		        $gtime = strtotime($gmt_payment);  
		  
		        //此处编写回调处理逻辑  
		  
		        //处理成功一定要返回 success 这7个字符组成的字符串，  
		        //die('success');//响应success表示业务处理成功，告知支付宝无需在异步通知  
		          
		    }  
    	}
	}

	 /**
     * 模拟get请求
     * @param $url
     * @return mixed
     */
    public function get_curl_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print_r(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($result,TRUE);
    }
   

		/**
	 * 小程序支付
	 * $openid  用户openid
	 * $money   金额
	 * $url     回调地址
	 * $payNum  支付时的商家订单号
	 */
	function pay($openid,$money,$payNum,$url,$uid){
	    $arr = [];
	    $openid = $openid;//用户openid
	    include_once '../app/wxpay/lib2/WxPay.JsApiPay.php';
	    include_once '../app/wxpay/lib/WxPay.Api.php';
	    $money = $money;//金额
	    $money =  (float)substr(sprintf("%.3f",$money),0,-1);
	    $order_no = $payNum;//支付时的商家订单号
	    $input = new \WxPayUnifiedOrder();
	    // dump($input);
	    $input->SetBody("支付");
      $input->SetAttach("支付");
	    // $input->Setprepay_id("100");
	    $input->SetOut_trade_no($order_no);//自定义订单号
	    $mymoney = $money*100;//金额分转元，*100
	    $input->SetTotal_fee($mymoney);//总金额
	    // $input->SetTime_start(date("YmdHis"));
	    // $input->SetTime_expire(date("YmdHis", time() + 600));
      $input->SetGoods_tag("微信支付");
	    // $input->SetTimeStamp(time());
	    $url = $url;//回调地址
	    //dump(url);
	    $input->SetNotify_url($url);
	    $input->SetTrade_type("JSAPI");
	    $input->SetOpenid($openid);
	    // dump($input);
	    $order = \WxPayApi::unifiedOrder($input);

	    $tools = new \JsApiPay();
	    $jsApiParameters = $tools->GetJsApiParameters($order);
      $list = $input->GetValues();
      $list['timeStamp'] = time();
      $data['money'] = $money;
      $data['source_id'] = $uid;
      $data['source'] = 0;
      $data['pay_way'] = 1;
      $data['status'] = 1;
      $data['out_trade_no'] = $list['out_trade_no'];
      // 增加一条充值订单数据并返回订单ID
      $add = Db::table('social_recharge_log')->insertGetId($data);
	    $data = json_decode($jsApiParameters,true);
      $data['out_trade_no'] = $list['out_trade_no'];
      // dump($data);
	    return $data;
	}
	 /*
 * 我的订单-待支付-立即支付
 */
    public function paywx(Request $request)
    {
        $openid = $request->input('openid');
        // $openid = 'o1zzM4nrtrJtCwmWHfCHeuMboJ5U';
        if($openid){
            $money = $request->input('money') ? $request->input('money') : 1;
            $payNum = date('YmdHis') . rand(1111,9999);
            $url = 'https://b.shidaichuxing.com/api/setorder/returnurl';//回调地址
            // 获取绑定的用户信息
            if(!empty($request->get('id'))){
                $uid = $request->get('id');
            }
            $result = $this -> pay($openid,$money,$payNum,$url,$uid);
            $arr['data'] = $result;
            $arr['err_code'] = '1000';
            $arr['err_msg'] = '生成订单成功';
        }else{
            $arr['err_code'] = '1001';
            $arr['err_msg'] = '生成订单失败,没有收到openid'; 
        }
        // $openid = "ol-Gh0TxQ90GUJy28FISB6snvC1g";
          
        echo json_encode($arr);
    }

    /*
     * 获取用户登录信息
     */
    public function getOpenid(Request $request)
    {
        $arr = [];
        $code = $request->input('code');
        $SECRET = 'd85ce9c54a6b0d0636c11f8c7a8014f4';
        $APPID = 'wxe5b2b29d2bd6a56c';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$APPID.'&secret='.$SECRET.'&js_code='.$code.'&grant_type=authorization_code';
        $res=$this->curlGet($url);
        $reqData = json_decode($res, true);
        $key = $reqData['session_key'];
        $openid = $reqData['openid'];
        $arr['openid'] = $openid;
        $arr['err_code'] = '1000';
        $arr['err_msg'] = '请求成功';
        echo  json_encode($arr);
    }
    /**
	 * GET方式获取远程url数据
	 * @param $url 远程地址
	 * @param $data GET数据
	 * @return url返回数据
	 */
	function curlGet($url,$data=""){
	    $ch=curl_init();
	    $header[]="Accept-Charset: utf-8";
	    curl_setopt($ch,CURLOPT_URL,$url);
	    curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"GET");
	    curl_setopt($ch,CURLOPT_TIMEOUT,500);
	    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
	    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
	    curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
	    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (compatible; MSIE 5.01;Window NT 5.0)');
	    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
	    curl_setopt($ch,CURLOPT_AUTOREFERER,1);
	    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	    curl_setopt($ch, CURLOPT_HEADER,0);
	    $temp=curl_exec($ch);
	    curl_close($ch);
	    return $temp;
	}


  // 回调地址
    public function returnurl(Request $Request) {
        ini_set('date.timezone', 'Asia/Shanghai');
        // require_once "../app/Wechat/lib/WxPay.Api.php";  
        // require_once "../app/Wechat/example/WxPay.AppPay.php";
        include_once '../app/wxpay/lib2/WxPay.JsApiPay.php';
        include_once '../app/wxpay/lib/WxPay.Api.php';
        
        error_reporting(E_ERROR);
        //初始化日志
        $logHandler = new \CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
        Log::Init($logHandler, 15);
        Log::DEBUG("begin notify");
        
        //在PayNotifyCallBack中重写了NotifyProcess，会发起一个订单支付状态查询，其实也可以不去查询，因为从php://input中已经可以获取到订单状态。file_get_contents("php://input")
        $notify = new \WxPayNotify();
        $notify = new \PayNotifyCallBack();
        $list = file_get_contents("php://input");
        // $notify->Handle(false);
        $result = $notify->GetValues();
        // dump($list);
        $mes = [];
        if ($result['trade_state'] == 'SUCCESS') {
            $num = $request['out_trade_no'] ? $request['out_trade_no'] : '';
            $data['status'] = 0;
            $data['created_at'] = date("Y-m-d H:i:s",time());
            $res = Db::table('social_recharge_log')->where('out_trade_no',$num)->update($data);
            $list = Db::table('social_recharge_log')->select('money','source_id')->where('out_trade_no',$num)->first();
            $list = json_decode(json_encode($list),true);
            // dump($list);
            $money = $list['money'];
            $uid = $list['source_id'];
            $user = Db::table('social_user')->where('id',$list['source_id'])->increment('sum_money',$money);
            if($res && $user){
                return ['code'=>1000,'message'=>'充值成功!'];
            }else{
                return ['code'=>1001,'message'=>'充值失败!'];
            }
        }else{
            $mes =   [
                    'message'=> '参数错误',
                    'code'=>'1003',
                ];
        }
        return json_encode($mes);
        Log::DEBUG("end notify");
        Log::INFO(str_repeat("=", 20));
}

    public function upload(Request $request)
    {
       // $file="uploads\/1234\/123456yuj.png";
        // echo json_encode($source);
        if(!$request->hasFile('source')){
            return '没有文件';
        }

        $file = $request->file('source');
        //判断文件上传过程中是否出错
        if(!$file->isValid()){
            return '文件上传出错';
        }

        $source = $this->makePhoto($request);
        $strs=stripslashes($source);
        return $strs;
       // echo json_encode($source);

    }
    private static  function makePhoto(Request $request )
    {
        $file = $request->file('source');

        if ($file) {
            //$domain = $_SERVER['HTTP_HOST'];
            $file_path = 'uploads/' . date("Ymd") . "/";
            $extension = $file->getClientOriginalExtension();
            $file_name = md5(time() . mt_rand(10, 99)) . '.' . $extension;
            $info = $file->move($file_path, $file_name);
            if (!$info) {
                //$error = $file->getError();
                return 'failed';
            }
            return   $file_path . $file_name;
        }
    }
    public function orderlist(Request $request )
    {
      $uid = $request->get('id');;//用户id
     // $uid = 2;
      $re = Db :: table('order')
          ->leftJoin('server_item','order.type','=','server_item.id')
          ->where('user_id',$uid)
          ->orderBy('created_at','desc')
          ->select('order.appointment','order.origin','order.end','order.status','server_item.name')
          ->get();
       $re = json_decode(json_encode($re),true);
       $arr = [];
       if(!empty($re)){
          foreach ($re as $key => &$value) {
              $value['appointment'] = date('Y-m-d H:i',$value['appointment']);
              if($value['status'] == 0){
                $value['statusName'] = '已取消';
                $arr['已取消订单'][] = $value;//已取消订单
              }elseif($value['status'] == 1){
                $value['statusName'] = '未开始';
                $arr['未开始订单'][] = $value;//未开始订单
              }elseif($value['status'] >= 9){
                $value['statusName'] = '已完成';
                $arr['已完成订单'][] = $value;//已完成订单
              }else{
                $value['statusName'] = '进行中';
                $arr['进行中订单'][] = $value;//进行中订单
              }

          }
       }else{
          $arr = [];
       }
  //  dump($arr);
    $retuen['data'] = $arr;
    $retuen['msg'] = '请求成功';
    echo json_encode($retuen);
  }
  //cip服务价格
  public function cipPrice(Request $request)
  {
    $area = Db :: table('region')->where('code',$request['area_code'])->first();
    $areaid = $area -> parentCode;
    $cips = Db :: table('company_fee')->where('area_id',$areaid)->first();
    $cips = $cips->cip_fee;
    $cip= (float)$cips;
    return $cip;
  }
  //企业或者个人的剩余可用金额，接送机次数，剩余企业分配的金额
  public function canUseMoney(Request $request)
  {
    $uid = $request->get('id');;//用户id
    if($request['types'] == 1){//个人
        $re = Db :: table('social_user')->where('id',$uid)->select('left_price','plane_left_num','p_plane_left_num','sum_money')->first();
        $re = json_decode(json_encode($re),true);
    }
    if ($request['types'] == 2) {//企业
      $com = Db :: table('social_user')->where('id',$uid)->select('company_id')->first();
      $company_id = $com -> company_id;
      $re = Db :: table('social_company')->where('id',$company_id)->select('account_money','plane_left_num')->first();
      $re = json_decode(json_encode($re),true);
    }
    $arr['code'] = '200';
    $arr['msg'] = '请求成功';
    $arr['data'] = $re;
    echo json_encode($arr);
  }
  //已开放的特色线路
  public function teseRout(Request $request)
  {
    $area = Db :: table('region')->where('code',$request['area_code'])->first();
    $areaid = $area -> parentCode;
    $parent_id = Db :: table('server_item')->where('name','特殊路线')->select('id')->first();
    $re = Db :: table('company_server_car')
            ->leftJoin('server_item','company_server_car.id','=','server_item.id')
            ->where('company_server_car',$areaid)
            ->where('server_item.parent_id',$parent_id -> id)
            ->select('id','name','picture')
            ->get();
    $re = json_decode(json_encode($re),true);
    $arr['code'] = '200';
    $arr['msg'] = '请求成功';
    $arr['data'] = $re;
    echo json_encode($arr);
  }
  //已开放的定制用车
   public function dingzhiRout(Request $request)
  {
    $area = Db :: table('region')->where('code',$request['area_code'])->first();
    $areaid = $area -> parentCode;
    $parent_id = Db :: table('server_item')->where('name','定制用车')->select('id')->first();
    $re = Db :: table('company_server_car')
            ->leftJoin('server_item','company_server_car.id','=','server_item.id')
            ->where('company_server_car',$areaid)
            ->where('server_item.parent_id',$parent_id -> id)
            ->select('id','name','picture')
            ->get();
    $re = json_decode(json_encode($re),true);
    $arr['code'] = '200';
    $arr['msg'] = '请求成功';
    $arr['data'] = $re;
    echo json_encode($arr);
  }
  function ali_pay(Request $request)
  {
      require_once '../app/alipay/aop/AopClient.php';
     
      $notify_url =  "";
     
      $c = new \AopClient;
      $c->signType = "RSA2";
      $c->appId = "2018052860271109";

      //支付宝公钥
      $c->alipayrsaPublicKey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhiBZEEqftuHPn86HdbhcoPmrjHErcoqHfhB25vk1kjmPlA5ovytISqsJZnV9JKSY+vQ53ITL/RpQjLKFmqjqZGm5GzOD2Q1Yfzacfptm8vFA2cZcjJ5sr4CXcYf56yq7YXX3JoGwSPlMzs9LJYXd5N/GRpwLHXNx+9eMCX31N+emCGwItJTIWjRk7F7Oq5YT2O/4nSw1XLce4GBKAkK/iDk0bBE6BHdAVLMnfOs26f/0hNCNkqiTSBekCIvKoy1PuXgEoxRVec7gVc+9IGZgGcROX6RN1qsOLIfsU74/6Sl7CTcn6Y4cjBerfskVDqCFDsoB3yUfU0KXhBhdd4+MDwIDAQAB";
      
      //应用秘钥
      $c->rsaPrivateKey ="MIIEogIBAAKCAQEApv0/3UzexQ6b827W/zYYeAAqiXAO/KHrJfdIZbazHshOpLdIIrk9XFZXGI+bZlgPFaTZsiyOidhjUj2NIx/uz3IW2d128e2EbUz5qs7DlhkZ3KvBcRRDGTgxUUaJHrail866VXZEyDPihmApz6lV2Tsyx712FroDfxnE1OB4rSOby/1BWuHTRrE5Zsv+2K8QfRDUOaiM5dcKjYe5CIJJbnXUYf5QoKdwEGd37Ao3be04+sQnRUsS7qh/egJRLQgOgbXGwZBaq7PRzarg3zsfdxsw5wfZbLerfwYsnEGdVR5GOBnRIPqNFnOWyZok+coJ3PD21v9UrKIss5XxStyrYwIDAQABAoIBAHuuPssN0EFrnJ4kjiDgVCctGFRLJw5+bsfj6z9KnkhCW90r0sXFJWlqmX+bfaHDvwhs3MBWuAvotUeIRyyozhvfiIU8vohZPyglRxX3pm1ZkgobPF8gfsIDGKP19kFFTA/cEa6StkcCBtk4CD/CT89hRS8jaH9UrppI37w7taWl85gBEmiQSjRYVZg1YjxIj6RY/ucbvwIlOzhQMvo/3kUJQ4vep16e/vbuFCi5boMGt/PXlWUh+HDqmYqnrE1WpCITHRL+jmYgK2li/oj985X//ZxkGTWSash8wWWD8RDOK7KAqOeJ6Bdy3DWI+DZA7flPIe/P/rdlr4DWWHcs9kECgYEA1mgqLyLhWL0irqkHwNGWtgTg6u/30oaQJWC/VYVv/JLCcKOIG2JjuGYpm2rn8PAsSOqmDkdfhTlLWEW5CqPG71E0NmkHb4eYMQ+ryEx+HXvq3Vo386fE/OFmy8jz6QW3ruQr586PYMfARW9sFy9CWbDoyfVKywwFVrjt5iO1bdkCgYEAx2I9IQ/MvJXn2io0ljNBYrEvaK+iI7c0LQUP4wZApTl+++yxTUkzbEdhWYEq7cJPJrr0mGMJX//RFXS0/0okBc6lThJ6Gg4R9TPOEbz4TjjwYu1ROoucay11IlO6nADtefAETCJz3dggFzBBhCo3Kdzv6zyI0DfDbR5iH+Hd0ZsCgYAQwpXBl4VsDWTfqGDtxrR0SA9Y7ic+Mryj31s1kTe+064VZgMmuNs4t+u6tXGqGOwtSwJuDVA/NspX/SNI3KKZZIyjUDR/mGbiNupjvu8A2QX0BbBoAI5agjgp5+yBI6xHJJj2BuSYWSUDiIE3kr8qCbU4zE7rbmYgcFZQbiwpiQKBgFPNrNfqpilV8L+4IaZIIOF0i/K6b7IHXPzXNdg8Voub4Q3ObK+JZv3J+tb9/ac1lsM2rXwnlFcvVRhpl3H+Han7M2vfREcTRuUDQ0gdX1ixgghyq0OqTrKVxrgI7VSI50frZEMD8CN8pfBZLhB5FfqYjJcZOIAcEB4bOS8hZnSlAoGAf1sevv2FBMZ57YQcAbtw0AaudV8FNlv+Oj6w2RN6Q8/P11ihpFS6lZ7wDEaipjJxYo0t0DgLlIMPf1n4QVowewBJFHHTx7YaD6mPnPIB38JZ6+Av0G3AxUugW+GNJReNLXfScSOgbAB5PpyKDdovRo4DCogHtGYf/ymqjIWkqsM=";

      $content['subject'] = '时代出行支付';//商品的标题/交易标题/订单标题/订单关键字等。
      $uid = $uid = $request->get('id'); ;
      $trade_no = $request['num'];
      $money = $request['money'];
      $content['out_trade_no'] = $trade_no;//商户网站唯一订单号
      $content['total_amount'] =$money;//    订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]，
      $content['product_code'] = "QUICK_MSECURITY_PAY";//    销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
      $con = json_encode($content);//$content是biz_content的值,将之转化成字符串
      $param = array();
      $param['app_id'] = $c->appId;//支付宝分配给开发者的应用ID
      $param['method'] = 'alipay.trade.app.pay';//接口名称
      $param['charset'] = 'utf-8';//请求使用的编码格式
      $param['sign_type'] = 'RSA2';//商户生成签名字符串所使用的签名算法类型
      $param['timestamp'] = date("Y-m-d H:i:s");//发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"
      $param['version'] = '1.0';//调用的接口版本，固定为：1.0
      $param['notify_url'] = $notify_url;//支付宝服务器主动通知地址
      $param['biz_content'] = $con;//业务请求参数的集合,长度不限,json格式
      //生成签名
      $paramStr = $c->getSignContent($param);
      $sign = $c->alonersaSign($paramStr,$c->rsaPrivateKey,'RSA2');
      $param['sign'] = $sign;
      $result = $c->getSignContentUrlencode($param);//返回给客户端
      $arr = ['key'=>$result];
      $a = json_encode($result);
      //dump($a);
      return json_encode($arr) ;
  }
}